<?php
namespace Wap\Controller;
use Think\Controller;
use Org\Util\Wechat;

class AutoMissionController extends Controller {
	
	private $fromtime;
	private $endtime;
	private $canGeneralUnorderAllOrder;
	private $curPeriod;
	private $curGroup;
	private $openid;
	public function _initialize() {
		// 当前正在进行的一期
		$condition = array('status' => C('p_status_go'));
		$this->curPeriod = M('period')->where($condition)->find();
		// 无当前进行的,退出
		if(!$this->curPeriod) {
			//\Think\Log::write('当前无进行中的期数，退出所有自动任务');
			exit;
		}
		$this->curGroup = M('group')->where(array('is_use' => 1))->select();
		if(!$this->curGroup) {
			\Think\Log::write('当前无启用的用户组,请至少启用一组用户');
			exit;
		}
		$this->chkPeriodTime();
	} 
	
	public function index() {
		$this->generateUnorderAllOrder();
	}
	/*
	 * 	自动生成未下单的订单
	 */
	public function generateUnorderAllOrder() {
		//\Think\Log::write('生成未下单用户的订单 -> periodid =' . $this->curPeriod['periodid']);
		if(!$this->canGeneralUnorderAllOrder) {
			\Think\Log::write('当前不允许生成，截止时间未到!');
			exit;
		}
		if($this->curPeriod['dogeneral'] == 1) {
			\Think\Log::write("这期的自动订单已经生成 => " . dump($this->curPeriod, false));
			exit;
		}
		// 查询出未自订的用户
		$condition_1 = array();
		$condition_1['opid'] = $this->curPeriod['periodid'];
		// 查出当期已点菜的用户
		$orderUsers = M('order')->field('basketid')->where($condition_1)->select();
		$orderUsersArr = array();
		foreach($orderUsers as $ouser) {
			$orderUsersArr[] = $ouser['basketid'];
		}
		// 查询出取消点菜的用户
		$cancelUsers = M('wxuser')->field('basketid,colid,openid')->where(array('cancelorder' => 1))->select();
		
		foreach($cancelUsers as $cuser) {
			$orderUsersArr[] = $cuser['basketid'];
		}
		
		$condition_2 = array();
		$collocation_names = C('collocation_names');
		// 合格的用户：有套餐号 + 菜篮子号 + 非取消当期配送
		/*
		$condition_2['colid'] = array('neq', '');
		//$condition_2['basketid'] = array('neq', 0);
		//$condition_2['cancelorder'] = array('eq', 0);
		*/
		if(!empty($orderUsersArr)) {
			$condition_2['a.basketid'] = array('not in', $orderUsersArr);
		}
		$condition_2['gid'] = array('eq', $this->curGroup['id']);
		$unorderUsers = M('user_group')
			->alias('a')
			->join('__WXUSER__ as b ON a.basketid = b.basketid')
			->where($condition_2)
			->getField('a.basketid as abasketid, b.openid as bopenid, b.colid as bcolid');
		if($unorderUsers || $cancelUsers){	
			// 根据用户套餐id，生成当期订单
			foreach($unorderUsers as $unoUser) {
				$colid = $unoUser['bcolid'];
				$opid = $this->curPeriod['periodid'];
				$openid = empty($unoUser['bopenid'])?'':$unoUser['bopenid'];
				$basketid = $unoUser['abasketid'];
				$ordertype = 1;		// ordertype:(0:手工 1:自动 2:取消订单)
				$this->createOrder($colid, $opid, $openid, $basketid, $ordertype);
			}
			
			foreach($cancelUsers as $user) {
				$colid = $user['colid'];
				$opid = $this->curPeriod['periodid'];
				$openid = $user['openid'];				// 取消订单用户，肯定是绑定用户
				$basketid = $user['basketid'];
				$ordertype = 2;							// ordertype:(0:手工 1:自动 2:取消订单)
				$this->createOrder($colid, $opid, $openid, $basketid, $ordertype);
			}
			
			// 标识这期已经自动生成完成
			$condition_3 = array('periodid' => $this->curPeriod['periodid']);
			$data_1 = array('doGeneral' => 1);
			$doGenrRes = M('period')->where($condition_3)->save($data_1);
			if($doGenrRes) {
				\Think\Log::write('自动生成订单成功');
			} else {
				\Think\Log::write('自动生成订单失败');
			}
		}else {
			\Think\Log::write('这期都已生成!');
		}
	}
	
	private function createOrder($colid, $opid, $openid, $basketid, $ordertype) {
		//\Think\Log::write('自动任务 -》 创建订单 ' . $colid . '-' . $opid . '-'. $openid);
		// 查询出套餐菜品s
		$condition['colname'] = $colid;
		$colinfo = M('period_collocation')->where($condition)->find();
		$condition_1['pc_colid'] = $colinfo['pcolid'];
		$period_collocation_item_m = M('period_collocation_item');
		$cbpFoods = $period_collocation_item_m->join('__FOOD__ ON __FOOD__.ID = __PERIOD_COLLOCATION_ITEM__.FOODID')->where($condition_1)->select();
		//\Think\Log::write('菜品有 =》'.dump($cbpFoods, false));
		
		$foods = array();
		foreach($cbpFoods as $cbpFood) {
			$foods['colfood'][$cbpFood['id']] = array('num' => 1, 'name' => $cbpFood['foodname'], 'ftype'=> 'colfood');
		}
		
		$oid 		= time().substr(microtime(),2,6).rand(0,9);
		$opid		= $opid;
		$ofoods 	= serialize($foods);
		$state 		= C('UNSEND');	// 0 未发货 1 已发货 2 用户已收货
		$istmsg 	= 0; 	// 0 未发送 已发货模板消息
		$mark		= '';
		$addtime 	= time();
		$odata = array(
			'oid'		=> $oid,
			'opid'		=> $opid,
			'openid'	=> $openid,
			'basketid'	=> $basketid,
			'ofoods'	=> $ofoods,
			'colname'	=> $colid,
			'state'		=> $state,	// 未发货
			'autoOrder'	=> $ordertype,
			'istmsg'	=> $istmsg,
			'mark'		=> $mark,
			'addtime'	=> $addtime,
			'sendtime'	=> ''
		);
		
		$addRes = M('order')->add($odata);
	}
	
	/*
	 *	关闭当期
	 *	当期且自动生成任务已经完成
	 * 	比结束时间推迟 5分钟执行关闭期数操作, 方便自动生成订单
	 */
	public function closePeriodStatus() {	
		//\Think\Log::write('关闭当期');
		$now_clock_sec   = time(date("Y-m-d"));	
		//\Think\Log::write('当前时间:结束时间 = ' . $now_clock_sec . '-' . ($this->endtime + 60*5) );
		if($now_clock_sec > ($this->endtime + 60*2) && $this->curPeriod){
			$condition_1 = array();
			$condition_1['periodid'] = $this->curPeriod['periodid'];
			$condition_1['doGeneral'] = 1;
			
			// 关闭当期
			$data_1 = array('status' => C('p_status_close'));
			$res_1 = M('period')->where($condition_1)->save($data_1);
			// 重置当期取消配送用户为 需要配送 状态
			$cond_2 = array('cancelorder' => 1);
			$data_2 = array('cancelorder' => 0);
			$res_2 = M('wxuser')->where($cond_2)->save($data_2);
			
			if($res_1) {
				\Think\Log::write('关闭 期数:' . $this->curPeriod['periodid'] . '成功');
				// Todo...发送一条消息
			} else {
				\Think\Log::write('关闭 期数:' . $this->curPeriod['periodid'] . '失败');
			}
		}
	}
	
	public function sendOrderMsg() {
		set_time_limit(0);
		$now_clock_sec = time(date("Y-m-d"));	
		// 时间大于 & 状态是进行 & 未群发
		if($now_clock_sec > $this->fromtime && $this->curPeriod['status'] == C('p_status_go') && $this->curPeriod['dosendmsg'] == 0) {
			$pname = $this->curPeriod['pname'];
			/*
			$condition_1['basketid'] = array('neq', 0);
			$condition_1['colid'] = array('neq', '');
			$users = M('wxuser')->where($condition_1)->select();
			*/
			$id_array = $this->curGroup;
			$ids = array_column(array_filter($id_array,function($val){
				if(array_keys($val)[0] == "id"){
					return $val["id"];
				}else{
					return false;
				}
			}),"id");
			$condition_1 = array();
			$condition_1['a.gid'] 	= array('in', $ids);
			$condition_1['a.openid'] = array('neq', '');
			$users = M('user_group')
				->alias('a')
				->join('__WXUSER__ as b ON a.basketid = b.basketid')
				->where($condition_1)
				->getField('a.openid as openid, a.basketid as basketid, b.nickname as nickname');
			\Think\Log::write('发送消息 套餐用户 => ' . dump($users, false));
			$time = date("Y-m-d H:i");
			\Think\Log::write('开始发送消息啦');
			foreach($users as $user) {
				$month = (int)date("m");
				$day = date("d");
				
				$result = pushWXTplMsg($user['openid'], $user['nickname'],$this->curPeriod, false);
				\Think\Log::write("pushWXTplMsg(res, errcode, msgid) =>".dump($result, false));
				sleep(20);
			}
			$condition_2 = array('periodid' => $this->curPeriod['periodid']);
			$data_2 = array('doSendMsg' => 1);
			M('period')->where($condition_2)->save($data_2);
			//\Think\Log::write("第$pname期群发完成");
		} else {
			\Think\Log::write('已发送模板消息');
		}
	}
	
	private function chkPeriodTime() {
		$now_clock_sec = time(date("Y-m-d"));	// 当前时间
		$this->fromtime = $this->curPeriod['fromtime'];
		$this->endtime = $this->curPeriod['endtime'];
		//\Think\Log::write('当前时间 -> ' . $now_clock_sec);
		//\Think\Log::write('起止时间 -> '.$this->fromtime . '-'.$this->endtime);
		if($now_clock_sec > $this->fromtime && $now_clock_sec < $this->endtime) {
			//\Think\Log::write('canOrder -> true');
			$this->canGeneralUnorderAllOrder = false;
		} elseif($now_clock_sec >= $this->endtime) {
			//\Think\Log::write('canOrder -> false');
			$this->canGeneralUnorderAllOrder = true;
		} elseif($now_clock_sec < $this->fromtime) {
			$this->canGeneralUnorderAllOrder = false;
		}
	}
}
?>